package com.situ.company.web220111.util;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;

public class FmtRequest {

    /**
     * 根据请求的参数情况反射得到实体类的对象（请求的参数名与实体类的属性名一致）
     *
     * @param req
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseModel(HttpServletRequest req, Class<T> clazz) {
        T obj = null; // 将T类型的对象定义出来

        try {
            obj = clazz.newInstance();  // 用反射得到T类型的对象

        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
        Map<String, String[]> map = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String name = entry.getKey();
            if ("action".equals(name))
                continue;
            try {
                Field field = clazz.getDeclaredField(name);
                field.setAccessible(true);
                field.set(obj, entry.getValue()[0]);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    /**
     * 根据映射关系得到实体类对象（请求的参数名与实体类的属性名不一致）
     *
     * @param req
     * @param clazz
     * @param fields key=属性名 value=参数名  参数与属性名不一致时
     * @param <T>
     * @return
     */
    public static <T> T parseModel(HttpServletRequest req, Class<T> clazz, Map<String, String> fields) {
        T obj = null; // 将T类型的对象定义出来
        try {
            obj = clazz.newInstance();  // 用反射得到T类型的对象

        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
        for (Map.Entry<String, String> entry : fields.entrySet()) {
            String name = entry.getKey();
            String val = req.getParameter(entry.getValue());
            try {
                Field field = clazz.getDeclaredField(name);
                field.setAccessible(true);
                field.set(obj, val);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

    public static void write(Writer writer, String val) {
        try {
            writer.write(val);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer = null;
    }

    public static void write(Writer wr, Object val) {
        if (val instanceof Collection<?>) {
            write(wr, new JSONArray((Collection<?>) val).toString());
        } else if (val instanceof String) {
            write(wr, val.toString());
        } else if (val instanceof Map<?, ?>) {
            write(wr, new JSONObject((Map<?, ?>) val).toString());
        } else {
            write(wr, new JSONObject(val).toString());
        }
    }
}
